// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// d [author] rhyme_lph
// V [email]  rhymelph@gmail.com
// Y [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/employee_contact_entity.dart';
import 'package:finance_app/src/entities/leave_item_entity.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/form_utils.dart';
import 'package:finance_app/src/widgets/button/normal_border_button.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/button/normal_text_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/attach_file_form.dart';
import 'package:finance_app/src/widgets/form/column_between_item_form.dart';
import 'package:finance_app/src/widgets/form/form_edit_status_inherited_widget.dart';
import 'package:finance_app/src/widgets/form/status_line_form.dart';
import 'package:finance_app/src/widgets/form/text_area_input_form.dart';
import 'package:finance_app/src/widgets/form/value_select_form.dart';
import 'package:finance_app/src/widgets/select/normal_radio.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/hr_payroll/leave/new_leave_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:tuple/tuple.dart';
export 'package:finance_app/src/entities/leave_item_entity.dart';

@RouterMeta(paramName: "newLeavePage")
class NewLeavePage extends StatefulWidget {
  final LeaveItemEntity data;

  const NewLeavePage({Key key, this.data}) : super(key: key);

  @override
  _NewLeavePageState createState() => _NewLeavePageState();
}

class _NewLeavePageState extends State<NewLeavePage>
    with PagePresenter<NewLeavePage, NewLeaveProvider> {
  TabController tabController;

  String get title => provider.id == null
      ? S.current.new_leave
      : provider.isEdit == true
          ? S.current.edit_leave
          : S.current.leave;

  Widget get rightButton => listBuilder<bool>(
        selector: (_, __) => __.isEdit == false && provider.id != null,
        builder: (BuildContext context, bool value, Widget child) =>
            value ? _buildPopButton() : _buildSaveBtn(),
      );

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
          titleWidget: listBuilder<bool>(
            selector: (_, __) => __.isEdit,
            builder: (BuildContext context, bool value, Widget child) =>
                Text(title),
          ),
          actions: [
            rightButton,
          ]);

  Widget _buildPopButton() => listBuilder<List<String>>(
        selector: (_, __) => List.from(__.menuList),
        builder: (BuildContext context, List<String> value, Widget child) =>
            value.length == 0
                ? Container()
                : NormalMorePopupButton(
                    onSelect: provider.onSelectMenu,
                    menuList: value,
                  ),
      );

  Widget _buildSaveBtn() {
    return listBuilder<bool>(
      selector: (_, __) => pageStatus != PageStatus.loading,
      builder: (BuildContext context, bool value, Widget child) => value == true
          ? NormalSaveTextButton(
              onTap: provider.onSave,
            )
          : Container(),
    );
  }

  @override
  void initState() {
    provider.initData(widget.data);
    super.initState();
  }

  @override
  Widget wrapperBody(Widget child) {
    return listBuilder<bool>(
        selector: (_, __) => __.isEdit == true || provider.id == null,
        builder: (BuildContext context, bool value, Widget child) =>
            FormEditStatusInheritedWidget(
              isEdit: value,
              child: child,
            ),
        child: child);
  }

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: ListView(
          children: [
            listBuilder<String>(
              selector: (_, __) => __.statusType,
              builder: (BuildContext context, String value, Widget child) =>
                  StatusLineForm(
                status: value,
                model: ReimburseModel.leave,
              ),
            ),
            FormStatusWidget(
              disable: listBuilder<String>(
                selector: (_, __) =>
                    __.statusType == 'rejected' ? __.rejectReason ?? '' : null,
                builder: (BuildContext context, String value, Widget child) =>
                    value != null
                        ? ValueSelectForm(
                            title: S.current.reasons_optional,
                            value: value,
                            onTap: provider.onSelectEmployee,
                            valueColor: aceRedColor,
                          )
                        : Container(),
              ),
              enable: Container(),
            ),
            listBuilder<String>(
              selector: (_, __) => FormUtils.getEmployeeName(__.employee),
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.employee_name,
                value: value,
                onTap: Config.isStaff ? null : provider.onSelectEmployee,
              ),
            ),
            listBuilder<Tuple2<EmployeeContactEmployeeLeaves, bool>>(
              selector: (_, __) => Tuple2(
                  __.leaveData,
                  __.leaveData != null &&
                      FormEditStatusInheritedWidget.ofEnable(_)),
              builder: (BuildContext context,
                      Tuple2<EmployeeContactEmployeeLeaves, bool> value,
                      Widget child) =>
                  value.item2 == true
                      ? PressedOpacityButton(
                          onPressed: provider.onSelectLeaveType,
                          child: ColumnBetweenItemForm(
                            leftTitle: S.current.leave_type,
                            leftValue: Config.settingData.leaveType
                                    .firstWhere(
                                        (element) =>
                                            element.key == value.item1?.type,
                                        orElse: () => null)
                                    ?.name ??
                                '${value.item1.name}',
                            rightTitle: S.current.balance_days,
                            rightValue: ((value.item1?.total ?? 0) -
                                    (value.item1?.used ?? 0))
                                .toString(),
                          ),
                        )
                      : ValueSelectForm(
                          title: S.current.leave_type,
                          onTap: provider.onSelectLeaveType,
                          value: value.item1?.name,
                        ),
            ),
            FormStatusWidget(
              enable: AppSpaces.grayH6,
              disable: Container(),
            ),
            FormStatusWidget(
              enable: Column(
                children: [
                  listBuilder<String>(
                    selector: (_, __) =>
                        DateTimeUtils.formatGlobalDateTime(__.startDate),
                    builder:
                        (BuildContext context, String value, Widget child) =>
                            ValueSelectForm(
                      title: S.current.start_date,
                      value: value,
                      onTap: provider.onChangeStartDate,
                    ),
                  ),
                  listBuilder<String>(
                    selector: (_, __) => __.startString,
                    builder:
                        (BuildContext context, String value, Widget child) =>
                            NormalFormWrapper(
                      hasBottomBorder: true,
                      topPadding: getDp(19),
                      bottomPadding: getDp(19),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: provider.timing
                            .map((e) => PressedOpacityButton(
                                  onPressed: () => provider.onSelectStart(e),
                                  child: NormalRadio(
                                    title: e,
                                    isSelect: e == value,
                                  ),
                                ))
                            .toList(),
                      ),
                    ),
                  ),
                ],
              ),
              disable: ColumnBetweenItemForm(
                leftTitle: S.current.start_date,
                leftValue:
                    DateTimeUtils.formatGlobalDateTime(provider.startDate),
                rightValue: provider.startString,
                rightTitle: S.current.am_pm,
                hasBottomBorder: true,
              ),
            ),
            FormStatusWidget(
              enable: Column(
                children: [
                  listBuilder<Tuple2<String, bool>>(
                    selector: (_, __) => Tuple2(
                        DateTimeUtils.formatGlobalDateTime(__.endDate),
                        __.hasError),
                    builder: (BuildContext context, Tuple2<String, bool> value,
                            Widget child) =>
                        ValueSelectForm(
                      title: S.current.end_date,
                      value: value.item1,
                      onTap: provider.onChangeEndDate,
                      hasError: value.item2,
                      errorText: S.current
                          .insufficient_leave_balance_please_select_again,
                    ),
                  ),
                  listBuilder<String>(
                    selector: (_, __) => __.endString,
                    builder:
                        (BuildContext context, String value, Widget child) =>
                            NormalFormWrapper(
                      hasBottomBorder: true,
                      topPadding: getDp(19),
                      bottomPadding: getDp(19),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: provider.timing
                            .map((e) => PressedOpacityButton(
                                  onPressed: () => provider.onSelectEnd(e),
                                  child: NormalRadio(
                                    title: e,
                                    isSelect: e == value,
                                  ),
                                ))
                            .toList(),
                      ),
                    ),
                  ),
                ],
              ),
              disable: ColumnBetweenItemForm(
                leftTitle: S.current.end_date,
                leftValue: DateTimeUtils.formatGlobalDateTime(provider.endDate),
                rightValue: provider.endString,
                rightTitle: S.current.am_pm,
                hasBottomBorder: true,
              ),
            ),
            FormStatusWidget(
              enable: AppSpaces.grayH6,
              disable: Container(),
            ),
            FormStatusWidget(
              enable: listBuilder<num>(
                selector: (_, __) => __.leaverDay,
                builder: (BuildContext context, num value, Widget child) =>
                    _buildLeaveApplied(value),
              ),
              disable: Container(),
            ),
            FormStatusWidget(
              enable: AppSpaces.grayH6,
              disable: Container(),
            ),
            TextAreaInputForm(
              title: S.current.additional_notes_optional,
              controller: provider.notesController,
              focusNode: provider.notesFocusNode,
            ),
            AppSpaces.h25,
            NormalFormWrapper(
              topPadding: 0.0,
              child:
                  listBuilder<Tuple2<List<String>, List<OcrAttachmentEntity>>>(
                selector: (_, __) => Tuple2(
                    List.from(__.files), List.from(__.attachments ?? [])),
                builder: (BuildContext context,
                        Tuple2<List<String>, List<OcrAttachmentEntity>> value,
                        Widget child) =>
                    AttachFileForm(
                  onAdd: provider.onAddAttachment,
                  files: value.item1,
                  onSelectFile: provider.onSelectFile,
                  attachments: value.item2,
                  onSelectAttachment: provider.onSelectAttachment,
                ),
              ),
            ),
            FormStatusWidget(
              enable: Container(),
              disable: listBuilder<List<String>>(
                selector: (_, __) => List.from(__.menuList),
                builder:
                    (BuildContext context, List<String> value, Widget child) =>
                        Visibility(
                  child: Column(
                    children: [
                      if (value.contains('Approve'))
                        NormalBorderButton(
                          title: S.current.approve,
                          isFit: true,
                          onTap: provider.onApprove,
                        ),
                      if (value.contains('Reject'))
                        Padding(
                          padding: EdgeInsets.only(top: getDp(15)),
                          child: NormalBorderButton(
                            isFit: true,
                            title: S.current.reject,
                            onTap: provider.onReject,
                          ),
                        ),
                      if (value.contains('Withdraw'))
                        NormalBorderButton(
                          title: S.current.withdraw,
                          isFit: true,
                          onTap: provider.onWithdraw,
                        ),
                    ],
                  ),
                  visible: value.length > 0,
                ),
              ),
            )
          ],
        ),
      );

  DefaultTextStyle _buildLeaveApplied(num days) {
    return DefaultTextStyle(
      style: TextStyle(
        color: aceDarkGrayColor,
        fontSize: getSp(16),
        fontWeight: FontWeight.w700,
        height: 14 / 16,
        fontFamily: "DinRoundPro",
      ),
      child: NormalFormWrapper(
        child: Row(
          children: [
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  S.current.total_leave_applied,
                ),
                SizedBox(
                  height: getDp(9),
                ),
                Text(
                  S.current.excluding_public_holiday,
                  style: TextStyle(
                      fontSize: getSp(14), fontWeight: FontWeight.w400),
                ),
              ],
            )),
            Text('${CashUtils.formatDay(days)} day${days > 1 ? 's' : ''}'),
          ],
        ),
      ),
    );
  }
}
